package top.hmtools.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import top.hmtools.HCHandle.HttpClientHandleTools;
import top.hmtools.base.StringTools;
import top.hmtools.model.MessageBean;
import top.hmtools.model.MsgTemplateBean;
import top.hmtools.model.ReturnInfoBean;
import top.hmtools.model.ReturnInfoBean.EStatus;
import top.hmtools.security.AESTools;

/**
 * 对接亿美的短信发送适配器
 * @author Jianghaibo
 *
 */
@Component
public class EmayAdapter extends BaseAdapter {
    
    @Value("${emay.isEnable:false}")
    private boolean isEnable;
    
    /**
     * 网关URL
     */
    @Value("${emay.url:}")
    private String url;;
    
    /**
     * 账号
     */
    @Value("${emay.appId:}")
    private String appId;;
    
    /**
     * 密钥
     */
    @Value("${emay.secretkey:}")
    private String secretkey;;

    /**
     * <br>方法说明
     * <br>输入参数说明
     * <br>输出参数说明
     */
    @Override
    boolean isEnable() {
        if(StringTools.isAnyBlank(this.url,this.appId,this.secretkey)){
            return false;
        }else{
            return this.isEnable;
        }
    }

    /**
     * <br>方法说明
     * <br>输入参数说明
     * <br>输出参数说明
     */
    @Override
    void init() {
        //skip
    }

    @Override
    ReturnInfoBean sendMsg(MsgTemplateBean msgTemplateBean,
            MessageBean messageBean) {
        ReturnInfoBean result = new ReturnInfoBean(EStatus.FAIL);
        result.setMessageBean(messageBean);
        result.setMsgTemplateBean(msgTemplateBean);
        
        //组装消息体
        Map<String,String> emayMsg = new HashMap<String,String>();
        emayMsg.put("mobile", messageBean.getPhoneNO());
        String content = msgTemplateBean.getContent();
        Map<String, String> contents = messageBean.getContents();
        for(Entry<String, String> item:contents.entrySet()){
            content = content.replaceAll(item.getKey(), item.getValue());
        }
        emayMsg.put("content", "【"+messageBean.getSign()+"】"+content);
        emayMsg.put("customSmsId", messageBean.getId());
        messageBean.setSendDateTime(new Date());
        emayMsg.put("requestTime", String.valueOf(messageBean.getSendDateTime().getTime()));
        int validPeriodTime = messageBean.getValidPeriodTime();
        emayMsg.put("requestValidPeriod", String.valueOf(validPeriodTime>0?validPeriodTime:30));
        
        //转换成json
        String emayMsgJson = JSON.toJSONString(emayMsg);
        
        //转换成byte
        CloseableHttpResponse response = null;
        InputStream responseContent = null;
        try {
            //加密内容
            byte[] emayMsgBytes  = emayMsgJson.getBytes("UTF-8");
            byte[] data = AESTools.encryptData(this.secretkey.getBytes(), emayMsgBytes);
            
            //组装请求
            CloseableHttpClient httpClient = HttpClientHandleTools.getPoolHttpClient();
            HttpPost post = new HttpPost(this.url);
            post.setHeader("appId", this.appId);
            ByteArrayEntity entity = new ByteArrayEntity(data);
            post.setEntity(entity);
            
            //执行http请求
            response = httpClient.execute(post);
            
            //解析结果
            Header firstHeader = response.getFirstHeader("result");
            String responseStatus = firstHeader.getValue();
            if(StringTools.isNotBlank(responseStatus) && "SUCCESS".equals(responseStatus)){
                result.setStatus(EStatus.SUCCESS);
                
                responseContent = response.getEntity().getContent();
                byte[] responseBytes = IOUtils.toByteArray(responseContent);
                byte[] decryptData = AESTools.decryptData(this.secretkey.getBytes(), responseBytes);
                String string = IOUtils.toString(decryptData, "UTF-8");
                String smsId = JSON.parseObject(string).getString("smsId");
                result.setOutId(smsId);
            }
            result.setRtnInfo(responseStatus);
        } catch ( InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | IOException e) {
            this.logger.error("发送消息失败："+e.getMessage(),e);
            result.setStatus(EStatus.FAIL);
            result.setRtnInfo(e.getMessage());
        }finally{
            if(responseContent != null){
                try {
                    responseContent.close();
                } catch (IOException e) {
                }
            }
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
        }
        return result;
    }

    @Override
    List<ReturnInfoBean> sendMsg(MsgTemplateBean msgTemplateBean,
            MessageBean... messageBean) {
        // TODO Auto-generated method stub
        return null;
    }

}
